﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zocono.WCS.Domain.DomainRepository;
using Zocono.WCS.Domain.EntityInfo;
using Zocono.WCS.Infrastructure.ApllicationDto.DtoWcsManage;
using SqlSugar;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Infrastructure.ApllicationDto;

namespace Zocono.WCS.Domain.LogDomain
{
    public class OperateLogService : IOperateLogService
    {

        private readonly IMapper _Mapper;
        private readonly IOperateLogInfoRepository _IOperateLogInfoRepository;
        private readonly ISnowflake _Snowflake;


        public OperateLogService(IMapper mapper, IOperateLogInfoRepository iOperateLogInfoRepository, ISnowflake snowflake)
        {
            _Mapper = mapper;
            _IOperateLogInfoRepository = iOperateLogInfoRepository;
            _Snowflake = snowflake;
        }

        public async Task<bool> CreateOperateLogInfoAsync(OperateLogInfoDto operateLogInfoDto)
        {

            OperateLogInfo operateLogInfo = new OperateLogInfo();

            _Mapper.Map(operateLogInfoDto, operateLogInfo);

            operateLogInfo.OperateID=_Snowflake.GetId();
            return await _IOperateLogInfoRepository.InsertAsync(operateLogInfo);
        }

        public async Task<PageDto<OperateLogInfoDto>> GetOperateLogInfoAsync(OperateLogInfoDto operateLogInfoDto)
        {
            PageModel page = new PageModel { PageIndex = operateLogInfoDto.PageIndex, PageSize = operateLogInfoDto.PageSize};
            PageDto<OperateLogInfoDto> pageDto = new PageDto<OperateLogInfoDto>();
            RefAsync<int> totalNumber = 0;

            OperateLogInfo operateLogInfo = new OperateLogInfo();
            _Mapper.Map(operateLogInfoDto, operateLogInfo);
            var exp = Expressionable.Create<OperateLogInfo>();
            exp.AndIF(!string.IsNullOrEmpty(operateLogInfo.OperateType), l => l.OperateType == operateLogInfo.OperateType);
            exp.AndIF(operateLogInfoDto.IsCheckTime, l => l.OperateTime > operateLogInfo.OperateTimeStart && l.OperateTime < operateLogInfo.OperateTimeEnd);

            var result = await _IOperateLogInfoRepository.AsSugarClient().Queryable<OperateLogInfo>().Where(exp.ToExpression())
                 .Select(l => new OperateLogInfoDto
                 {
                     OperateID = l.OperateID,
                     OperateUserID=l.OperateUserID,
                     OperateUserName=l.OperateUserName,
                     OperateDetail=l.OperateDetail,
                     OperateTime=l.OperateTime,
                     OperateType=l.OperateType
                 })
                 .ToPageListAsync(page.PageIndex,page.PageSize, totalNumber);
            pageDto.Result = result;
            pageDto.Total = totalNumber;
            return pageDto;
        }
    }
}
